from app import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash

class User(db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    full_name = db.Column(db.String(100))
    age = db.Column(db.Integer)
    gender = db.Column(db.String(10))
    height = db.Column(db.Float)
    weight = db.Column(db.Float)
    
    # 定义关联关系 - 一对多
    vital_signs = db.relationship('VitalSigns', backref='user', lazy='dynamic', cascade='all, delete-orphan')
    body_compositions = db.relationship('BodyComposition', backref='user', lazy='dynamic', cascade='all, delete-orphan')
    blood_tests = db.relationship('BloodTest', backref='user', lazy='dynamic', cascade='all, delete-orphan')
    daily_activities = db.relationship('DailyActivity', backref='user', lazy='dynamic', cascade='all, delete-orphan')
    health_assessments = db.relationship('HealthAssessment', backref='user', lazy='dynamic', cascade='all, delete-orphan')
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
    
    def to_dict(self):
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'full_name': self.full_name,
            'age': self.age,
            'gender': self.gender,
            'height': self.height,
            'weight': self.weight,
            'created_at': self.created_at.isoformat()
        }